package com.luoy.netty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author LUOYUAN
 * @create 2019-07-08-13:54
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    /**
     *
     * 客户端读取到数据后干什么
     * @param channelHandlerContext
     * @param byteBuf
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object obj) throws Exception {
       // System.out.println("client accept:  "+ byteBuf.toString(CharsetUtil.UTF_8));

        System.out.println("client accept:  "+ obj);
       ByteBuf byteBuf =  (ByteBuf)obj;
        System.out.println("client accept:  "+ byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 客户端被通知channel活跃以后,做事
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception{

        //往服务器写数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,netty：",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
